Golang : Match strings by wildcard patterns with filepath.Match() function
Problem:
You want to match strings using the same wildcard patterns commonly used in Linux/Unix shells such as *.go
or *data[0-9]*
. How to do that?
Solution:
package main
import (
"fmt"
"path/filepath"
)
func main() {
filename := "start.txt"
pattern := "*art*"
matched, err := filepath.Match(pattern, filename)
if err != nil {
fmt.Println(err)
}
fmt.Println(matched)
//---------------------------------
pattern = "*fart*"
matched, err = filepath.Match(pattern, filename)
if err != nil {
fmt.Println(err)
}
fmt.Println(matched)
//---------------------------------
filename = "data123.csv"
pattern = "data[0-9]*"
matched, err = filepath.Match(pattern, filename)
if err != nil {
fmt.Println(err)
}
fmt.Println(matched)
}
Output :
true
false
true
NOTES: This example is for matching strings. For filenames in the current or specific directory. See this tutorial https://socketloop.com/tutorials/golang-use-wildcard-patterns-with-filepath-glob-example
It should work as well if you replace filepath.Match()
with path.Match()
Reference:
See also : Golang : Use wildcard patterns with filepath.Glob() example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.6k Swift : Get substring with rangeOfString() function example
+8.2k Golang : Find relative luminance or color brightness
+16.6k Golang : Delete files by extension
+18.2k Golang : Get command line arguments
+7.4k Linux : How to fix Brother HL-1110 printing blank page problem
+7.7k Golang : Generate human readable password
+11.2k Google Maps URL parameters configuration
+13.4k Golang : Generate Code128 barcode
+16.8k Golang : read gzipped http response
+13.1k Golang : Convert(cast) uintptr to string example
+17.7k Golang : Parse date string and convert to dd-mm-yyyy format
+8.7k Golang : Set or add headers for many or different handlers